# -*- encoding:utf8 -*-
import re
from datetime import time,timedelta
from attendance.convert import str2dt
from attendance.workday import is_workday


def application_span(start_time,end_time,workshift='08:30-17:30'):
    ls= divide_timeblock(start_time, end_time, workshift)
    return timeblock_span(ls)

def timeblock_span(ls):
    """
    计算由divide_timeblock返回的列表，时间跨度的长度
    """
    span = timedelta(0)
    for l in ls:
        workday,workshif=is_workday(str2dt(l['start_time']).date())
        if workday:
            span += (str2dt(l['end_time']) - str2dt(l['start_time']))
    span = int(span.total_seconds() / 60)
    return span    

def divide_timeblock(start_time,end_time,workshift='08:30-17:30'):
    """分割LeaveApplication对象成连续的时间段
    Args:
    Retrun:
    [{'start_time':...,'end_time:...}]
    
    """
    rt = []
    if isinstance(start_time,(str,unicode)):
        start_time=str2dt(start_time)
    if isinstance(end_time,(str,unicode)):
        end_time=str2dt(end_time)

    pos = start_time
    #workshift = leave.staff.workshift
    mt = re.search(r'(\d+):(\d+)-(\d+):(\d+)', workshift)
    if mt:
        sud_start = time(int(mt.group(1)), int(mt.group(2)))
        sud_end = time(int(mt.group(3)), int(mt.group(4)))
    else:
        sud_start = time(8, 30)
        sud_end = time(17, 30)
    while True:
        if pos >= end_time:
            break
        pos_sud_end = pos.replace(hour=sud_end.hour, minute=sud_end.minute)
        for start, end in _filter_noon(pos, end_time):
            if pos_sud_end <= end:
                end = pos_sud_end
            start_timestr = start.strftime('%Y-%m-%d %H:%M')
            end_timestr = end.strftime('%Y-%m-%d %H:%M')
            rt.append({'start_time': start_timestr,
                       'end_time': end_timestr
                       })
        pos = pos + timedelta(days=1)
        pos = pos.replace(hour=sud_start.hour, minute=sud_start.minute)
    return rt

def _filter_noon(start, end):
    """过滤掉start.day当日的中午时段，以迭代器器的形式返回
    """
    start_noon = start.replace(hour=12, minute=30)
    end_noon = start.replace(hour=13, minute=30)
    if start <= start_noon:
        if end <= start_noon:
            yield start, end
        elif end > end_noon:
            yield start, start_noon
            yield end_noon, end
        else:
            yield start, start_noon
    else:
        yield end_noon, end